package com.beverages.orders.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beverages.orders.client.MerchantIndividualClient;
import com.beverages.orders.constant.OrderStatus;
import com.beverages.orders.entity.Orders;
import com.beverages.orders.entity.dto.OrdersDTO;
import com.beverages.orders.service.IOrdersService;
import com.beverages.orders.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/merchant/orders")
public class OrdersController {

    @Autowired
    private MerchantIndividualClient merchantIndividualClient;

    @Resource
    private IOrdersService ordersService;

    @GetMapping("/page")
    public Result<IPage<OrdersDTO>> findPage(@RequestParam Integer pageNum,
                                             @RequestParam Integer pageSize,
                                             @RequestParam(defaultValue = "") String orderNumber) {
        IPage<Orders> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();

        if (orderNumber != null && !orderNumber.trim().equals("")) {
            queryWrapper.eq("order_number", orderNumber.trim());
        }

        IPage<Orders> resultPage = ordersService.page(page, queryWrapper);

        // 将查询结果转换为 DTO 列表
        List<OrdersDTO> dtoList = resultPage.getRecords().stream().map(orders -> {
            return ordersService.convertOrdersEntityToOrdersDTO(orders);
        }).collect(Collectors.toList());

        // 创建新的 IPage 对象来封装 DTO 列表
        IPage<OrdersDTO> dtoPage = new Page<>(pageNum, pageSize, resultPage.getTotal());
        dtoPage.setRecords(dtoList);

        // Return the DTO page instead of the original resultPage
        return Result.success(dtoPage);
    }

    @GetMapping("/{orderId}")
    public Result<OrdersDTO> findOne(@PathVariable("orderId") Integer orderId){
        return Result.success(ordersService.convertOrdersEntityToOrdersDTO(ordersService.getById(orderId)));
    }

    @GetMapping("/orderNumber/{orderNumber}")
    public Result<OrdersDTO> findOneByOrderNumber(@PathVariable("orderNumber") String orderNumber){
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number",orderNumber.trim());
        Orders uniqueOrder = ordersService.getOne(queryWrapper);
        return Result.success(ordersService.convertOrdersEntityToOrdersDTO(uniqueOrder));
    }

    @GetMapping("/pending/{capacity}")
    public Result<List<Integer>> getPendingOrdersIds(@PathVariable("capacity") Integer capacity){
        return Result.success(ordersService.getFilteredOrdersByCapacity(capacity));
    }

    @GetMapping("/update-completion-status")
    public Result updateCompletionStatus(
            @RequestParam(name = "orderId") Integer orderId,
            @RequestParam(name = "completionStatus") Integer completionStatus){
        System.out.println("orderId:"+orderId);
        System.out.println("completionStatus:"+completionStatus);
        Orders order = ordersService.getById(orderId);
        order.setCompletionStatus(completionStatus);
        if(completionStatus == 3){
            Date currentDate = new Date();
            order.setCompletionTime(currentDate);
        }
        ordersService.saveOrUpdate(order);
        return Result.success();
    }

    @GetMapping("/update-place-status")
    public Result updatePlaceStatus(
            @RequestParam(name = "orderId") Integer orderId,
            @RequestParam(name = "placeStatus") Integer placeStatus){
        Orders order = ordersService.getById(orderId);
        order.setPlaceStatus(placeStatus);
        ordersService.saveOrUpdate(order);
        return Result.success();
    }

    @GetMapping("/fill-holder")
    public Result fillHolderIds(
            @RequestParam(name = "orderId") Integer orderId,
            @RequestParam(name = "holderId") Integer holderId) {
        Orders order = ordersService.getById(orderId);
        if(order.getHolderIds().equals("0")){
            order.setHolderIds(holderId.toString());
        }else {
            order.setHolderIds(order.getHolderIds() + "," + holderId.toString());
        }
        ordersService.saveOrUpdate(order);
        return Result.success();
    }

    @GetMapping("/empty-holder")
    public Result emptyHolderIds(
            @RequestParam(name = "orderId") Integer orderId,
            @RequestParam(name = "holderId") Integer holderId) {
        Orders order = ordersService.getById(orderId);
        String holderIds = order.getHolderIds();

        if (holderIds != null && !holderIds.isEmpty()) {
            // 将 holderIds 字符串拆分成 List 进行处理
            List<String> holderIdList = new ArrayList<>(Arrays.asList(holderIds.split(",")));

            // 判断传入的 holderId 是否存在于 holderIdList 中
            String targetHolderId = String.valueOf(holderId);
            if (holderIdList.contains(targetHolderId)) {
                // 如果存在，移除该 holderId
                holderIdList.remove(targetHolderId);

                // 如果移除后，列表为空，则设置为 "0"
                if (holderIdList.isEmpty()) {
                    holderIds = "0";
                } else {
                    // 否则，重新拼接剩下的 holderIds
                    holderIds = String.join(",", holderIdList);
                }
            }
            order.setHolderIds(holderIds);
        }

        ordersService.saveOrUpdate(order);
        return Result.success();
    }

    @GetMapping("/cancel-order")
    public Result cancelOrder(@RequestParam(name = "orderNumber") String orderNumber){
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number",orderNumber.trim());
        Orders uniqueOrder = ordersService.getOne(queryWrapper);

        uniqueOrder.setOrderStatus(OrderStatus.cancelled);
        ordersService.saveOrUpdate(uniqueOrder);
        merchantIndividualClient.refundToCustomer(uniqueOrder.getCustomerId(), uniqueOrder.getTotalPrice());
        return Result.success();
    }
}
